package org.extframework.ld.control;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.extframework.ld.bean.Power;
import org.extframework.ld.content.XmlContent;
import org.extframework.ld.content.model.XmlMenuNode;
import org.extframework.ld.sort.XmlMenuSort;

/**
 * @author : Dong.Li
 * @created : 2013-1-17
 * @version : 1.0
 * @description :
 */
public class ExtXmlControl {
	
	
	public static String getRootMenu(List<Power> powers) {
		return getRootMenu((Power[]) powers.toArray(new Power[0]));
	}

	public static String getRootMenu(Power[] powers) {
		List<XmlMenuNode> xmns = new ArrayList<XmlMenuNode>();
		Map<String,Power> powerMaps = new HashMap<String,Power>();
		for (Power power : powers) {
			powerMaps.put(power.getPowerId(), power);
		}
		for (XmlMenuNode xmn : XmlContent.getRootNodes()) {
			if (powerMaps.containsKey(xmn.getId())) {
				XmlMenuNode node = new XmlMenuNode();
				node.setId(xmn.getId());
				node.setText(xmn.getText());
				node.setLeaf(xmn.isLeaf());
				node.setSort(xmn.getSort());
				node.setIconCls(xmn.getIconCls());
				xmns.add(node);
			}
		}
		Collections.sort(xmns, new XmlMenuSort());
		return ((String) ExtJsonControl.MenuDate(xmns.toArray()));
	}

	public static String getMenuNodes(String parentMenuId, List<Power> powers) {
		return getMenuNodes(parentMenuId,
				(Power[]) powers.toArray(new Power[0]));
	}

	public static String getMenuNodes(String parentMenuId, Power[] powers) {
		List<XmlMenuNode> xmns = new ArrayList<XmlMenuNode>();
		Map<String,Power> powerMaps = new HashMap<String,Power>();
		for (Power power : powers)
			powerMaps.put(power.getPowerId(), power);
		try {
			for (XmlMenuNode xmn : XmlContent.getNode(parentMenuId)
					.getChiledMenuNodes())
				if (powerMaps.containsKey(xmn.getId())) {
					XmlMenuNode node = new XmlMenuNode();
					node.setId(xmn.getId());
					node.setText(xmn.getText());
					node.setLeaf(xmn.isLeaf());
					node.setSort(xmn.getSort());
					node.setIconCls(xmn.getIconCls());
					xmns.add(node);
				}
		} catch (Exception e) {
			e.printStackTrace();
		}
		Collections.sort(xmns, new XmlMenuSort());
		return ExtJsonControl.MenuDate(xmns.toArray());
	}
}
